import advListView from '$v/advList';
import {
    isLoginRequest
} from '../api/admin'
import {
    addAdvRequest,
    advListRequest,
    deleteAdvRequest,
    getUpdateDataRequest,
    updateAdvRequest
} from '../api/adv';

const showAdvList = async function (res, pageNo = 1, everyNum = 3) {
    let findResult = null
    try {
        findResult = await advListRequest(pageNo, everyNum)
    } catch (e) {
        alert(e.message)
    }
    const {
        advList,
        pageCount
    } = findResult
    res.render(advListView({
        advList,
        pageCount
    }))
}

export default async (req, res) => {
    //路由切换的时候验证登录
    try {
        await isLoginRequest();
    } catch (e) {
        //请求异常后提示用户
        alert("有异常" + e.message)

        //判断是否是权限异常
        if (!e.isLogin) {
            return router.go("/login");
        }
    }
    showAdvList(res)
    document.onclick = async function (e) {
        if (e.target.id === 'adv-save') {
            const myForm = new FormData(document.advForm)
            if (!myForm.get("advTitle") || !myForm.get("advType") || !myForm.get("advOrder") || !myForm.get("advPic")) {
                return alert("添加的内容不能有空的！！！！")
            }
            //发送请求
            try {
                await addAdvRequest(myForm)
                alert("添加广告成功")
                //关闭添加广告的弹窗
                document.getElementById("addClose").click();

                //清空表单
                document.advForm.reset();
                
                showAdvList(res)
            } catch (e) {
                alert("添加广告异常" + e.message)
            }
        }
        //删除广告逻辑

        if (e.target.nodeName === "BUTTON" && e.target.classList.contains("btn-delete")) {
            //获取按钮上保存的 当前数据的 _id
            const _id = e.target.dataset.id;
            
            // console.log(_id);
            try {
                await deleteAdvRequest(_id);
                alert("删除数据成功")
                
                showAdvList(res)
            } catch (e) {
                alert("删除数据失败" + e.message)

                //判断是否是权限异常
                if (!e.isLogin) {
                    //关闭添加广告的弹窗再跳转
                    document.getElementById("addClose").click();
                    return router.go("/login");
                }
            }

        }
        //查看更新广告
        if (e.target.nodeName === "BUTTON" && e.target.classList.contains("btn-update")) {
            const _id = e.target.dataset.id
            console.log(_id);
            try {
                const updateData = await getUpdateDataRequest(_id);
                console.log(updateData);

                //把数据放入更新的窗口中
                // console.log(document.updateForm);
                document.updateForm.advTitle.value = updateData.advTitle;
                document.updateForm.advType.value = updateData.advType;
                document.updateForm.advOrder.value = updateData.advOrder;

                //给当前弹窗的更新按钮上添加一个自定义属性 保存当前数据的id  方便以后提交
                document.getElementById('adv-update').dataset.id = updateData._id;
            } catch (e) {
                alert("更新查询失败" + e.message)
            }

        }
        //点击更新逻辑
        if (e.target.id === "adv-update") {
            const _id = e.target.dataset.id;
            //收集表单数据 使用FormData
            const myForm = new FormData(document.updateForm);
            if (!myForm.get("advTitle") || !myForm.get("advType") || !myForm.get("advOrder") || !myForm.get("advPic")) {
                return alert("添加的内容不能有空的！！！！")
            }

            try {
                await updateAdvRequest(myForm, _id);
                console.log("更新成功");

                //重新渲染视图
                //调用获取adv列表的函数
                
                showAdvList(res)

                //关闭添加广告的弹窗再跳转
                document.getElementById("updateClose").click();

                document.querySelector('.modal-backdrop').style.display = "none";

            } catch (e) {
                alert("更新广告异常" + e.message);
                //判断是否是权限异常
                if (!e.isLogin) {
                    //关闭添加广告的弹窗再跳转
                    document.getElementById("updateClose").click();
                    return router.go("/login");
                }
            }
        }

        //点击页码
        if (e.target.nodeName === "SPAN" && e.target.parentNode.id === "page") {
            //重新发送请求 并传入当前要加载的页码
            const pageNo = +e.target.dataset.pageno;
            showAdvList(res, pageNo)
        }

    }
}

document.onchange = function (e) {
    if (e.target.id === "advPic") {
        const reader = new FileReader();
        reader.readAsDataURL(e.target.files[0])
        reader.onload = function (e) {
            // console.log(e.target.result);
            //把当前的读取的base64格式 给到img
            const oPreImg = document.getElementById('preImg');
            oPreImg.src = e.target.result;
            oPreImg.style.display = "block"
        }
    }
    if (e.target.id === "advUp") {
        const reader = new FileReader();
        reader.readAsDataURL(e.target.files[0])
        reader.onload = function (e) {
            // console.log(e.target.result);
            //把当前的读取的base64格式 给到img
            const oPreImg = document.getElementById('predImg');
            oPreImg.src = e.target.result;
            oPreImg.style.display = "block"
        }
    }
}